package com.vma.jifu.service.impl;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.jifu.bizModel.model.*;
import com.vma.jifu.service.AgentService;
import com.vma.tools.AppException;
import com.vma.tools.OrderUtils;
import com.vma.tools.StringUtils;

import java.util.*;

/**
 * Created by chenzui on 2017/6/21.
 */
public class AgentServiceImpl implements AgentService {
    public Page<User> getFirstAgent(Integer cPage,Integer pSize,Integer userId, String account) {
        String condition = "";
        List param = new ArrayList();
        param.add(userId);
        if(!StringUtils.isEmpty(account)){
            condition += "AND (login_account like ? OR phone like ? OR nick_name like ?)";
            param.add("%"+account+"%");
            param.add("%"+account+"%");
            param.add("%"+account+"%");
        }
        Page<User> userPage = User.dao.paginate(cPage,pSize,
                "SELECT * ",
                "FROM user WHERE first_parent_user_id = ? "+condition,param.toArray());
        return userPage;
    }

    public Page<ReturnCharge> gryReturnList(Integer cPage, Integer pSize, Integer userId, String start, String end) {
        Page<ReturnCharge> returns = ReturnCharge.dao.paginate(cPage,pSize,
                "SELECT rc.* ",
                "FROM return_charge rc,order_list ol\n" +
                        "WHERE ol.id = rc.order_id\n" +
                        "AND ol.user_id = ? \n" +
                        "AND ol.create_time >= ?\n" +
                        "AND ol.create_time <= ?",userId,start,end);
        return returns;
    }

    public JoinFee qryAgentArea(String province, String city, String area) {
        Provinces provinces = Provinces.dao.findFirst("select * from provinces where province = ?",province);
        Cities cityObj = Cities.dao.findFirst("select * from cities where city = ?",city);
        Areas areaObj = Areas.dao.findFirst("select * from areas where area = ?",area);
        if(provinces == null || areaObj == null){
            throw new AppException("-1","省市县查询异常");
        }

        JoinFee join = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE province = ? AND area = ?",
                provinces.getProvinceid(),areaObj.getAreaid());
        if(join == null){
            throw new AppException("-2","加盟区域查询异常");
        }else {
            if(join.getStatus().equals("1")){
                throw new AppException("-3","该区域已经加盟");
            }else {
                return join;
            }
        }
    }

    public AgentOrder commitAgentInfo(Integer joinId,Integer userId, String tjren, String phone, String agentName) {
        Date date = new Date();
        JoinFee joinFee = JoinFee.dao.findById(joinId);
        User userTj = null;
        if(!StringUtils.isEmpty(tjren)) {
            userTj = User.dao.findFirst("SELECT * FROM user WHERE login_account = ?");
            if (userTj == null) {
                throw new AppException("-1", "推荐人账号信息错误");
            }
        }
        joinFee.setAgentName(agentName).setPhone(phone).setUserId(userId).update();
        AgentOrder agentOrder = new AgentOrder().setAgentOrderNbr(OrderUtils.generateOrderNbr())
                .setCharge(joinFee.getCastNum()).setStatus(0).setUserId(userId).setCreateTime(date)
                .setUpdateTime(date);
        agentOrder.save();

//        AgentFanli agentFanli = new AgentFanli().setTjUserId(userTj.getId())
//                .setUserId(userId).setCreateTime(date).setFee(joinFee.getCastNum()/10).setStatus(0).setOrderId(agentOrder.getId());
//        agentFanli.save();
        if(userTj != null) {
            TgAward tgAward = new TgAward().setCreateTime(date).setType(5).setFee(joinFee.getCastNum() / 10)
                    .setStatus(0).setUpdateTime(date).setUserId(userTj.getId()).setOrderId(agentOrder.getId());
            tgAward.save();
        }
        return agentOrder;
    }

    public boolean callBackForAgentCharge(String orderNbr, Integer type) {
        AgentOrder order = AgentOrder.dao.findFirst("SELECT * FROM agent_order WHERE agent_order_nbr = ? AND status = 0",orderNbr);
        if(order == null){
            return false;
        }

        //返利记录生效
        TgAward tgAward = TgAward.dao.findFirst("SELECT * FROM tg_award WHERE order_id = ? and type = 5",order.getId());
        tgAward.setStatus(1).update();
        //代理记录生效
        JoinFee joinFee = JoinFee.dao.findFirst("SELECT * FROM join_fee WHERE user_id = ?");
        joinFee.setStatus(1).update();
        //充值订单生效
        order.setStatus(1).setPayChannel(type).update();

        return true;
    }

    public void initJoinFee() {
        List<Provinces> provinces = Provinces.dao.find("select * from provinces");
        for(Provinces p : provinces){
            List<Cities> cities = Cities.dao.find("select * from cities where provinceid = ?",p.getProvinceid());
            for(Cities c:cities){
                List<Areas> areases = Areas.dao.find("select * from areas where cityid = ?",c.getCityid());
                for(Areas a:areases){
                    new JoinFee().setProvince(Integer.valueOf(p.getProvinceid()))
                            .setCity(Integer.valueOf(c.getCityid())).setArea(Integer.valueOf(a.getAreaid())).setCastNum(500000)
                            .setStatus(0).save();
                }
            }
        }
    }

    public Map initAgentPage(Integer userId) {
        JoinFee joinFee = JoinFee.dao.findFirst("select * from join_fee where user_id = ? and status = 1",userId);
        if(joinFee == null){
            throw new AppException("-1","无代理区域");
        }
        Record hasConfirm = Db.findFirst("SELECT ifnull(sum(fee),0) total FROM tg_award WHERE user_id = ? AND type = 4 AND status in (1,2,3)",userId);
        Record notConfirm = Db.findFirst("SELECT ifnull(sum(fee),0) total FROM tg_award WHERE user_id = ? AND type = 4 AND status in (0)",userId);
        Provinces provinces = Provinces.dao.findFirst("SELECT * FROM provinces WHERE provinceid = ?",joinFee.getProvince());
        Cities cities = Cities.dao.findFirst("SELECT * FROM cities WHERE cityid  = ?",joinFee.getCity());
        Areas areas = Areas.dao.findFirst("SELECT * FROM areas WHERE areaid = ?",joinFee.getArea());
        Map result = new HashMap();
        result.put("hasConfirm",hasConfirm.getBigDecimal("total").longValue());
        result.put("notConfirm",notConfirm.getBigDecimal("total").longValue());
        result.put("province",provinces.getProvince());
        result.put("city",cities.getCity());
        result.put("area",areas.getArea());
        result.put("areaId",areas.getAreaid());
        result.put("total",hasConfirm.getBigDecimal("total").longValue()+notConfirm.getBigDecimal("total").longValue());
        return result;
    }

    public Page<TgAward> qryAgentAwardList(Integer userId, Integer cPage, Integer pSize) {
        return TgAward.dao.paginate(cPage,pSize,
                "SELECT\n" +
                        "  u.login_account,\n" +
                        "  ao.create_time,\n" +
                        "  u.head_img,\n" +
                        "  ta.fee,\n" +
                        "  p.province,\n" +
                        "  c.city,\n" +
                        "  a.area",
                "FROM agent_order ao, tg_award ta, user u, join_fee jf, provinces p, cities c, areas a\n" +
                        "WHERE ao.id = ta.order_id\n" +
                        "      AND ta.type = 5\n" +
                        "      AND ta.status = 1\n" +
                        "      AND ao.user_id = u.id\n" +
                        "      AND ao.user_id = jf.user_id\n" +
                        "      AND jf.status = 1\n" +
                        "      AND jf.province = p.provinceid\n" +
                        "      AND jf.city = c.cityid\n" +
                        "      AND jf.area = a.areaid\n" +
                        "      AND ta.user_id = ?",userId);
    }

    public Long qryTotalTgAward(Integer userId) {
        return Db.findFirst(
                "SELECT ifnull(sum(fee),0) charge FROM tg_award WHERE type = 5 AND user_id = 9 AND status = 1")
                .getBigDecimal("charge").longValue();
    }

    public Integer checkArea(String province, String city, String area) {
        Provinces provinces = Provinces.dao.findFirst("select * from provinces where province like ?","%"+province+"%");
        Cities cities = Cities.dao.findFirst("select * from cities where city like ? and provinceid = ?","%"+city+"%",provinces.getProvinceid());
        Areas areas = Areas.dao.findFirst("select * from areas where area like ? and cityid = ?","%"+area+"%",cities.getCityid());
        if(areas == null){
            throw new AppException("-1","后台未查询到该区域");
        }else {
            JoinFee joinFee = JoinFee.dao.findFirst("select * from join_fee where area = ?",areas.getAreaid());
            if(joinFee == null){
                throw new AppException("-2","后台未查询到该区域加盟信息");
            }else {
                return joinFee.getCastNum();
            }
        }
    }

}
